package com.ruoyi.ruoyictmanage.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruoyi.ruoyictmanage.domain.entity.Line;

public class LineNameConverter implements Converter<Line> {
    @Override
    public Class<Line> supportJavaTypeKey() {
        return Line.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Line convertToJavaData(ReadConverterContext<?> context) {
        String cellValue = context.getReadCellData().getStringValue();
        if (cellValue == null) {
            // 尝试直接读取数字值
            Number numberValue = context.getReadCellData().getNumberValue();
            if (numberValue != null) {
                return new Line(numberValue.intValue());
            }
            return new Line(0); // 默认值
        }
        try {
            int lineId = Integer.parseInt(cellValue.trim()); // 解析为整数
            return new Line(lineId); // 创建 Line 对象
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("line_name 必须是整数，实际值: " + cellValue);
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(Line line, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(String.valueOf(line != null ? line.getLine_name() : ""));
    }
}